package com.spvs.approval.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spvs.approval.domain.ApprovalFromEntity;
import com.spvs.approval.domain.ApprovalSubmitEntity;
import com.spvs.approval.domain.vo.ApprovalFromVo;
import com.spvs.approval.domain.vo.ApprovalSubmitVo;
import com.spvs.approval.service.ApprovalFromService;
import com.spvs.approval.service.ApprovalSubmitService;
import com.spvs.approval.support.ApprovalBusinessContext;
import com.spvs.common.core.constant.SecurityConstants;
import com.spvs.common.core.utils.DateUtils;
import com.spvs.common.core.utils.poi.ExcelUtil;
import com.spvs.common.core.web.domain.AjaxResult;
import com.spvs.common.security.utils.SecurityUtils;
import com.spvs.system.api.IEquipDeptService;
import com.spvs.system.api.ILeaseOutService;
import com.spvs.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 审批表单信息表
 */
@RestController
@RequestMapping("/approval/approvalFrom")
public class ApprovalFromController {

    @Autowired
    private ApprovalFromService approvalFromService;
    @Autowired
    private ApprovalSubmitService approvalSubmitService;
    @Autowired
    private ILeaseOutService leaseOutService;
    @Autowired
    private IEquipDeptService equipDeptService;

    /**
     * 添加审批表单
     *
     * @param from
     * @return
     */
    @PostMapping("/addFrom")
    public AjaxResult addFrom(@RequestBody ApprovalFromVo from) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        from.setCreateUserId(Integer.parseInt(loginUser.getUserid().toString()));
        from.setCreateUserName(loginUser.getUsername());
        from.setStatus(ApprovalFromVo.APPROVAL_STATUS_NOT_STARTED);
        return approvalFromService.initiateApproval(from);
    }

    ;

    /**
     * 发起审批
     *
     * @param from
     * @return
     */
    @PostMapping("/initiateApproval")
    public AjaxResult initiateApproval(@RequestBody ApprovalFromVo from) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        from.setCreateUserId(Integer.parseInt(loginUser.getUserid().toString()));
        from.setCreateUserName(loginUser.getUsername());
        from.setStatus(ApprovalFromVo.APPROVAL_STATUS_IN_PROGRESS);
        return approvalFromService.initiateApproval(from);
    }

    ;

    /**
     * 修改审批表单
     *
     * @param approvalFromVo
     * @return
     */
    @PostMapping("/updateApproval")
    public AjaxResult updateApproval(@RequestBody ApprovalFromVo approvalFromVo) {
        if (null == approvalFromVo.getId()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            approvalFromVo.setCreateUserId(Integer.parseInt(loginUser.getUserid().toString()));
            approvalFromVo.setCreateUserName(loginUser.getUsername());
            approvalFromVo.setStatus(ApprovalFromVo.APPROVAL_STATUS_NOT_STARTED);
            return approvalFromService.initiateApproval(approvalFromVo);
        }
        return approvalFromService.updateApproval(approvalFromVo);
    }

    ;

    /**
     * 删除审批信息
     *
     * @param approvalFromVo
     * @return
     */
    @PostMapping("/deleteApproval")
    public AjaxResult deleteApproval(@RequestBody ApprovalFromVo approvalFromVo) {
        return approvalFromService.deleteApproval(approvalFromVo);
    }

    ;

    /**
     * 审批
     *
     * @param approvalSubmitVo
     * @return
     */
    @PostMapping("/approval")
    public AjaxResult approval(@RequestBody ApprovalSubmitVo approvalSubmitVo) {
        return approvalFromService.approval(approvalSubmitVo);
    }

    ;

    /**
     * 查看审批记录
     *
     * @param id
     * @return
     */
    @RequestMapping("/queryByRecords")
    public AjaxResult queryByRecords(@RequestParam Integer id) {
        return approvalFromService.queryByRecords(id);
    }

    ;

    /**
     * 按条件查询自己创建的审批信息
     *
     * @param param
     * @return
     */
    @PostMapping("/queryApprovalByLaunch")
    public AjaxResult queryApprovalByLaunch(@RequestBody Map<String, Object> param) {
        return approvalFromService.queryApprovalByLaunch(param);
    }

    ;

    /**
     * 按条件查询 审批人是自己的审批信息
     * 待我审批
     *
     * @param param
     * @return
     */
    @RequestMapping("/queryApprovalBy")
    public AjaxResult queryApprovalBy(@RequestBody Map<String, Object> param) {
        return approvalFromService.queryApprovalBy(param);
    }

    ;

    @RequestMapping("/queryFromById")
    public AjaxResult queryFromById(@NotNull @RequestParam Integer id) {
        ApprovalFromEntity from = approvalFromService.queryFromById(id);

        return AjaxResult.success(from);
    }

    ;

    @RequestMapping("/querySubmitById")
    public AjaxResult queryApprovalById(@NotNull @RequestParam Integer id) {
        ApprovalSubmitEntity entity = approvalSubmitService.getById(id);
        ApprovalFromEntity from = approvalFromService.getById(entity.getFromId());
        entity.setStatus(entity.getStatus());
        return AjaxResult.success(entity);
    }

    ;

    /**
     * 按用户查询最新审批的时间
     *
     * @param userId
     * @return
     */
    @RequestMapping("/queryLatestTime")
    public AjaxResult queryLatestTime(@NotNull @RequestParam String userId) {
        LambdaQueryWrapper<ApprovalSubmitEntity> qw = Wrappers.lambdaQuery();
        qw.select(ApprovalSubmitEntity::getCreateTime);
        qw.eq(ApprovalSubmitEntity::getApprovalStaffId, userId);
        qw.eq(ApprovalSubmitEntity::getApprovalStatus, ApprovalSubmitVo.APPROVAL_STATUS_NOT_STARTED);
        qw.orderByDesc(ApprovalSubmitEntity::getCreateTime);
        List<ApprovalSubmitEntity> list = approvalSubmitService.list(qw);
        if (null != list && !list.isEmpty()) {
            ApprovalSubmitEntity ApprovalSubmitEntity = list.get(0);
            Map<String, Object> map = new HashMap<>(2);
            map.put("latestTime", ApprovalSubmitEntity.getCreateTime().getTime());
            map.put("count", list.size());
            return AjaxResult.success(map);
        }
        return AjaxResult.success("暂无消息", null);
    }

    /**
     * 审批记录打印信息--租赁相关
     */
    @PostMapping("/leaseList")
    public AjaxResult leaseList(@RequestParam Integer id){
        //查询审批表单信息
        ApprovalFromEntity from = approvalFromService.getById(id);
        String businessId = from.getBusinessId();
        List<Map<String, String>> list = new ArrayList<>();
        if (from.getType().equals(ApprovalBusinessContext.TYPE_SBZL) || from.getType().equals(ApprovalBusinessContext.TYPE_SBTL)
                || from.getType().equals(ApprovalBusinessContext.TYPE_SBXZ )|| from.getType().equals(ApprovalBusinessContext.TYPE_SBTINGZ)) {
            //设备租赁
            AjaxResult info = leaseOutService.getInfo(businessId);
            if (info.isSuccess()) {
                if (info.get("data") != null) {
                    //查询租赁出厂详情
                    Map<String, Object> data = (Map<String, Object>) info.get("data");
                    if (data !=null){
                        AjaxResult info1 = equipDeptService.getInfo(Long.parseLong(data.get("applyUnitId").toString()), SecurityConstants.INNER);
                        if (info1.isSuccess()) {
                            if (info1.get("data") != null) {
                                Map<String, Object> data1 = (Map<String, Object>) info1.get("data");
                            }
                        }else{
                        }
                        String remark = data.get("remark").toString();
                        List<Map<String,Object>> equipLeaseBetweens = (List<Map<String, Object>>) data.get("equipLeaseBetweens");
                        if (CollectionUtils.isNotEmpty(equipLeaseBetweens)) {
                            for (int i = 0; i < equipLeaseBetweens.size(); i++) {
                                equipLeaseBetweens.get(i).put("remark",remark);
                            }
                        }
                    }
                }
            }
            return info;
        }else{
            return AjaxResult.error("与租赁无关");
        }
    }
    /**
     * 审批记录导出
     *
     * @return
     */
    @PostMapping("/exportApproval")
    public void export(HttpServletResponse response, @RequestParam Integer id) {
        if (null == id || id <= 0) {
            throw new RuntimeException("请求参数不正确");
        }
        String[] excelHeader = {
                "序号", "工作令", "编号", "设备名称", "规格型号", "单位", "数量", "性质", "备注"};

        String[] excelHeaderKey = {
                "xh", "gzl", "equipNum", "equipName", "equipModel"
                , "unit", "number", "xz", "bz"};

        String[] approvalexcelHeader = {
                "序号", "部门", "审批人", "审批意见", "审批状态"};

        String[] approvalexcelHeaderKey = {
                "xh", "deptName", "approvalName", "approvalYj", "approvalState"};
        //查询审批表单信息
        ApprovalFromEntity from = approvalFromService.getById(id);
        String businessId = from.getBusinessId();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        if (from.getType().equals(ApprovalBusinessContext.TYPE_SBZL) || from.getType().equals(ApprovalBusinessContext.TYPE_SBTL)
        || from.getType().equals(ApprovalBusinessContext.TYPE_SBXZ )|| from.getType().equals(ApprovalBusinessContext.TYPE_SBTINGZ)) {
            map.put("time", DateUtils.convertTimestampToDateString(from.getCreateTime(), DateUtils.YYYY_MM_DD_STR));
            map.put("headTitle", "永泰能源装备制造分公司大型设备出厂单");
            //设备租赁
            AjaxResult info = leaseOutService.getInfo(businessId);
            if (info.isSuccess()) {
                if (info.get("data") != null) {
                    //查询租赁出厂详情
                    Map<String, Object> data = (Map<String, Object>) info.get("data");
                    if (data !=null){
                        AjaxResult info1 = equipDeptService.getInfo(Long.parseLong(data.get("applyUnitId").toString()), SecurityConstants.INNER);
                        if (info1.isSuccess()) {
                            if (info1.get("data") != null) {
                                Map<String, Object> data1 = (Map<String, Object>) info1.get("data");
                                map.put("company", data1.get("deptName"));
                            }
                        }else{
                            map.put("company", "");
                        }
                        String remark = data.get("remark").toString();
                        map.put("leaseNum", data.get("leaseNum"));
                        List<Map<String,Object>> equipLeaseBetweens = (List<Map<String, Object>>) data.get("equipLeaseBetweens");
                        if (CollectionUtils.isNotEmpty(equipLeaseBetweens)) {
                            for (int i = 0; i < equipLeaseBetweens.size(); i++) {
                                Map<String, String> dataMap = new HashMap<>();
                                dataMap.put("xh", (i + 1) + "");
                                dataMap.put("gzl", "");
                                dataMap.put("equipNum", equipLeaseBetweens.get(i).get("equipNum").toString());
                                dataMap.put("equipName", equipLeaseBetweens.get(i).get("equipName").toString());
                                dataMap.put("equipModel", equipLeaseBetweens.get(i).get("equipModel").toString());
                                dataMap.put("unit", equipLeaseBetweens.get(i).get("unit").toString());
                                dataMap.put("number", equipLeaseBetweens.get(i).get("number").toString());
                                dataMap.put("xz", "租赁");
                                dataMap.put("bz", remark);
                                list.add(dataMap);
                            }
                        }
                        map.put("equipLeaseBetweens", equipLeaseBetweens);
                    }
                }
            }
        }
        // 审批详细记录
        map.put("approvalTitle", from.getTitle());
        map.put("approvalContent", from.getContent());
        // 查询审批的详细信息
        AjaxResult ajaxResult = approvalFromService.queryByRecords(from.getId());
        List<Map<String, String>> approvallist = new ArrayList<>();
        if (ajaxResult.isSuccess()){
            if (ajaxResult.get("data") != null){
                List<ApprovalSubmitEntity> approvalSuccesslist = (List<ApprovalSubmitEntity>) ajaxResult.get("data");
                if (CollectionUtils.isNotEmpty(approvalSuccesslist)){
                    for (int i = 0; i < approvalSuccesslist.size(); i++) {
                        Map<String, String> dataMap = new HashMap<>();
                        dataMap.put("xh",(i+1)+"");
                        dataMap.put("deptName",approvalSuccesslist.get(i).getApprovalDeptName());
                        dataMap.put("approvalName",approvalSuccesslist.get(i).getApprovalStaffName());
                        dataMap.put("approvalYj",approvalSuccesslist.get(i).getApprovalIdea());
                        // 审批状态 (101未开始   201 审批中  301通过  302 驳回)
                        Integer approvalStatus = approvalSuccesslist.get(i).getApprovalStatus();
                        switch (approvalStatus){
                            case 101:
                                dataMap.put("approvalState","未开始");
                                break;
                            case 201:
                                dataMap.put("approvalState","审批中");
                                break;
                            case 301:
                                dataMap.put("approvalState","通过");
                                break;
                            case 302:
                                dataMap.put("approvalState","驳回");
                                break;
                        }
                        approvallist.add(dataMap);
                    }
                }
            }
        }
        ExcelUtil.exportApprovalExcel(response, excelHeader, excelHeaderKey, "租赁出厂单及审批记录", "表1", map, list,approvalexcelHeader,approvalexcelHeaderKey,approvallist);
    }

}
